#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import re
import json
from typing import Dict, List, Any, Optional
from pathlib import Path

class MarkdownFormatParser:
    """Markdown格式规范解析器"""
    
    def __init__(self, md_file_path: str = "config/自动测试用例生成格式规范.md"):
        self.md_file_path = md_file_path
        self.field_specs = {}
        
    def parse_markdown_file(self) -> Dict[str, Any]:
        """
        解析markdown文档，提取字段格式规范
        
        Returns:
            解析后的字段规范字典
        """
        try:
            if not Path(self.md_file_path).exists():
                print(f"⚠️ Markdown文件不存在: {self.md_file_path}")
                return {}
            
            with open(self.md_file_path, 'r', encoding='utf-8') as f:
                content = f.read()
            
            return self._parse_content(content)
            
        except Exception as e:
            print(f"❌ 解析markdown文件失败: {e}")
            return {}
    
    def _parse_content(self, content: str) -> Dict[str, Any]:
        """解析markdown内容"""
        field_specs = {}
        
        # 使用正则表达式匹配字段规范
        # 匹配格式：2.x field_name\n类型：type\n标签：...\n格式要求：...
        pattern = r'2\.\d+\s+(\w+)\s*\n类型：([^，\n]+)[，\n]*标签：([^\n]+)\n格式要求：([\s\S]*?)(?=2\.\d+|$)'
        
        matches = re.findall(pattern, content)
        
        for match in matches:
            field_name, field_type, labels, requirements = match
            
            # 解析标签
            label_dict = self._parse_labels(labels)
            
            # 解析格式要求
            format_rules = self._parse_requirements(requirements)
            
            field_specs[field_name] = {
                "field_type": field_type.strip(),
                "labels": label_dict,
                "requirements": format_rules,
                "examples": self._extract_examples(requirements),
                "counter_examples": self._extract_counter_examples(requirements)
            }
        
        return field_specs
    
    def _parse_labels(self, labels: str) -> Dict[str, str]:
        """解析标签信息"""
        label_dict = {}
        
        # 匹配 zh_CN="xxx"，en_US="xxx" 格式
        zh_match = re.search(r'zh_CN="([^"]+)"', labels)
        en_match = re.search(r'en_US="([^"]+)"', labels)
        
        if zh_match:
            label_dict["zh_CN"] = zh_match.group(1)
        if en_match:
            label_dict["en_US"] = en_match.group(1)
        
        return label_dict
    
    def _parse_requirements(self, requirements: str) -> Dict[str, Any]:
        """解析格式要求"""
        rules = {}
        
        # 提取长度限制 - 改进正则表达式
        max_length_match = re.search(r'最大长度\s*(\d+)\s*字符', requirements)
        if max_length_match:
            rules["max_length"] = int(max_length_match.group(1))
        
        # 提取数值范围 - 改进正则表达式
        range_match = re.search(r'(\d+)\s*位以内整数.*?([-\d]+)\s*~\s*([-\d]+)', requirements)
        if range_match:
            rules["max_digits"] = int(range_match.group(1))
            rules["min_value"] = int(range_match.group(2))
            rules["max_value"] = int(range_match.group(3))
        
        # 提取小数位数限制 - 改进正则表达式
        decimal_match = re.search(r'整数部分≤(\d+)\s*位，小数部分≤(\d+)\s*位', requirements)
        if decimal_match:
            rules["integer_digits"] = int(decimal_match.group(1))
            rules["decimal_digits"] = int(decimal_match.group(2))
        
        # 提取日期格式
        date_format_match = re.search(r'格式：([A-Z\-]+)', requirements)
        if date_format_match:
            rules["date_format"] = date_format_match.group(1)
        
        # 提取字符数限制 - 改进正则表达式
        char_limit_match = re.search(r'总字符数\s*(\d+)-(\d+)', requirements)
        if char_limit_match:
            rules["min_chars"] = int(char_limit_match.group(1))
            rules["max_chars"] = int(char_limit_match.group(2))
        
        # 提取字符数上限
        char_max_match = re.search(r'总字符数≤(\d+)', requirements)
        if char_max_match:
            rules["max_chars"] = int(char_max_match.group(1))
        
        # 提取特殊要求
        if "包含@" in requirements:
            rules["contains_at"] = True
        if "包含dialing_code" in requirements:
            rules["has_dialing_code"] = True
        if "包含country_code" in requirements:
            rules["has_country_code"] = True
        if "包含number" in requirements:
            rules["has_number"] = True
        if "11位有效数字" in requirements or "11位数字" in requirements:
            rules["number_digits"] = 11
        if "包含zh_CN" in requirements:
            rules["has_zh_cn"] = True
        if "包含en_US" in requirements:
            rules["has_en_us"] = True
        if "仅支持true或false" in requirements:
            rules["boolean_only"] = True
        if "值必须为预设optionList" in requirements:
            rules["must_be_option_list"] = True
        
        return rules
    
    def _extract_examples(self, requirements: str) -> List[str]:
        """提取正例"""
        examples = []
        
        # 匹配正例部分
        examples_section = re.search(r'正例：\s*\n(.*?)(?=反例：|$)', requirements, re.DOTALL)
        if examples_section:
            examples_text = examples_section.group(1)
            # 提取JSON格式的示例
            json_matches = re.findall(r'"[^"]+":\s*[^,\n]+', examples_text)
            examples.extend(json_matches)
        
        return examples
    
    def _extract_counter_examples(self, requirements: str) -> List[str]:
        """提取反例"""
        counter_examples = []
        
        # 匹配反例部分
        counter_section = re.search(r'反例：\s*\n(.*?)(?=3\.|$)', requirements, re.DOTALL)
        if counter_section:
            counter_text = counter_section.group(1)
            # 提取JSON格式的反例
            json_matches = re.findall(r'"[^"]+":\s*[^,\n]+', counter_text)
            counter_examples.extend(json_matches)
        
        return counter_examples
    
    def get_field_types(self) -> List[str]:
        """获取所有字段类型"""
        specs = self.parse_markdown_file()
        return list(specs.keys())
    
    def get_field_spec(self, field_name: str) -> Optional[Dict[str, Any]]:
        """获取特定字段的规范"""
        specs = self.parse_markdown_file()
        return specs.get(field_name)
    
    def generate_format_summary(self) -> str:
        """生成格式规范摘要，用于AI提示词"""
        specs = self.parse_markdown_file()
        
        if not specs:
            return "无法解析格式规范文档"
        
        summary_lines = []
        summary_lines.append("参考格式规范（从markdown文档解析）：")
        
        for field_name, spec in specs.items():
            field_type = spec.get("field_type", "unknown")
            labels = spec.get("labels", {})
            requirements = spec.get("requirements", {})
            
            # 构建格式要求描述
            format_desc = self._build_format_description(field_type, requirements)
            
            summary_lines.append(f"- {field_name}（{field_type}）: {format_desc}")
        
        return "\n".join(summary_lines)
    
    def _build_format_description(self, field_type: str, requirements: Dict[str, Any]) -> str:
        """构建格式要求描述"""
        desc_parts = []
        
        if field_type == "text":
            if "max_length" in requirements:
                desc_parts.append(f"最大长度{requirements['max_length']}字符")
        
        elif field_type == "bigint":
            if "max_digits" in requirements:
                desc_parts.append(f"{requirements['max_digits']}位以内整数")
            if "min_value" in requirements and "max_value" in requirements:
                desc_parts.append(f"范围{requirements['min_value']}~{requirements['max_value']}")
        
        elif field_type in ["number", "decimal"]:
            if "integer_digits" in requirements:
                desc_parts.append(f"整数部分≤{requirements['integer_digits']}位")
            if "decimal_digits" in requirements:
                desc_parts.append(f"小数部分≤{requirements['decimal_digits']}位")
        
        elif field_type == "date":
            if "date_format" in requirements:
                desc_parts.append(f"格式{requirements['date_format']}")
        
        elif field_type == "datetime":
            desc_parts.append("支持字符串格式'YYYY-MM-DD HH:MM:SS'或时间戳")
        
        elif field_type == "mobileNumber":
            desc_parts.append("包含dialing_code、country_code、number三个字段")
            if "number_digits" in requirements:
                desc_parts.append(f"number为{requirements['number_digits']}位数字")
        
        elif field_type == "email":
            if requirements.get("contains_at"):
                desc_parts.append("包含@且@后有有效域名")
        
        elif field_type == "option":
            if requirements.get("must_be_option_list"):
                desc_parts.append("值必须为预设optionList中的apiName")
        
        elif field_type == "boolean":
            if requirements.get("boolean_only"):
                desc_parts.append("仅支持true或false")
        
        elif field_type in ["multilingual", "richText"]:
            if "max_chars" in requirements:
                desc_parts.append(f"总字符数≤{requirements['max_chars']}")
            if requirements.get("has_zh_cn"):
                desc_parts.append("包含zh_CN")
            if requirements.get("has_en_us"):
                desc_parts.append("包含en_US")
        
        return "，".join(desc_parts) if desc_parts else "无特殊限制"

def main():
    """测试函数"""
    parser = MarkdownFormatParser()
    
    print("=== Markdown格式规范解析器测试 ===")
    
    # 解析文档
    specs = parser.parse_markdown_file()
    
    print(f"\n解析到 {len(specs)} 个字段规范:")
    for field_name, spec in specs.items():
        print(f"  {field_name}: {spec['field_type']}")
    
    # 生成格式摘要
    print(f"\n格式规范摘要:")
    summary = parser.generate_format_summary()
    print(summary)

if __name__ == "__main__":
    main() 